/*
 * JBeagle - a Java toolkit for genetic algorithms.
 * 
 * Copyright (c) 2010 Matthijs Snel
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package jbeagle.core;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.StreamCorruptedException;
import java.util.Arrays;

import org.apache.log4j.Logger;

import jbeagle.config.Configuration;
import jbeagle.core.ops.GeneticOperator;
import jbeagle.core.select.Selector;
import jbeagle.config.Parser;

public class GAFactory {
	
	static Logger log = Logger.getLogger(GAFactory.class.toString());
	
	Configuration config;
	
	public GAFactory() {}
	
	public GAFactory( String filePath ) {
		config = Parser.parse(filePath);
	}

	@SuppressWarnings("unchecked")
	public GeneticAlgorithm create() {
		GeneticAlgorithm ga = new GeneticAlgorithm();
		if ( config.getObject("fitnessfunction") != null )
			ga.setFitnessFunction((FitnessFunction) config.getObject("fitnessfunction"));
		ga.setSelectionMethod( (Selector) config.getObject("selector") );
		//TODO set stopcondition using reflection as well
		ga.setStopCondition( ga.new StopCondition(config.getInt("numgen")) );
		for ( Object o : config.getConfig("operators").getObjects().values() )
			ga.addOperator((GeneticOperator) o);
		
		Configuration popConfig = config.getConfig("population");
		
		String file = popConfig.getString("file");
		Population pop;
		if ( file != null && !file.equals("") )
			pop = loadPopulationFromFile(file, (IndividualFactory) popConfig.getObject("factory"));
		else
			pop = (Population) popConfig.getObject("population");
		ga.setPopulation(pop);
		
		return ga;
	}
	
	public static Population loadPopulationFromFile(String file, IndividualFactory factory) {
		Population<Individual, ?> pop = null;
		ObjectInputStream ois = null;
		try {
			log.info("Trying to restore serialized population from file.");
			ois = new ObjectInputStream( new FileInputStream(file) );
			pop = (Population) ois.readObject();
		} catch (StreamCorruptedException sce) {
			//assume it's a text file then
			log.info("Not a binary file. Trying to create population from text file.");
			pop = loadPopulationFromTextFile(file, factory);
		} catch (Exception e) {
			log.warn("Problem trying to restore population from file: " + file 
					+ ": " + e + ".");
		} finally {
			try {
				if ( ois != null )
					ois.close();
			} catch (IOException ioe) {
				log.warn("Problem closing stream: " + ioe);
			}
		}
		
		return pop;
	}
	
	public static Population loadPopulationFromTextFile(String file, IndividualFactory factory) {
		Population pop = new Population();
		BufferedReader in = null;
		try {
			in = new BufferedReader( new FileReader(file) );
			String line = in.readLine();
			while ( line != null ) {
				//check if fitness is included
				int index = line.indexOf(",");
				double fitness = 0;
				if ( index > -1 ) {
					fitness = Double.parseDouble( line.substring(index+1) );
					line = line.substring(0, index);
				}
				String[] parts = line.split(" ");
				Individual ind = factory.createIndividual(Arrays.asList(parts));
				ind.setFitness(fitness);
				pop.add( ind );
				
				line = in.readLine();
			}
		} catch (FileNotFoundException e) {
			log.error("File " + file + " not found. Returning empty population.");
		} catch (IOException ioe) {
			log.error("Problem reading file " + file + ": " + ioe.getMessage() 
					+ ". Returning empty population.");
		}
		
		try {
			in.close();
		} catch (IOException ioe) {
			log.warn("Problem closing file " + file + ": " + ioe.getMessage());
		}
		
		return pop;
	}
}
